﻿using AutoMapper;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using WMS.FC.Domain.DataTransferObject.Cell;
using WMS.FC.Domain.DomainObject.System;
using WMS.FC.Domain.PersistenceObject.Business;
using WMS.FC.Domain.Repository;
using WMS.FC.Domain.Service.Cell.Interface;
using WMS.FC.Domain.Service.System;
using WMS.FC.Domain.Service.Tray.Interface;

namespace WMS.FC.Domain.Service.Tray
{
    public class AutoBindTrayService : ServiceBase, IAutoBindTrayService
    {
        protected readonly ITrayRepository trayRepository;
        protected readonly ITechnologyRepository technologyRepository;
        protected readonly IBindCellService bindCellService;

        public AutoBindTrayService(
            ILogger<ServiceBase> logger,
            IOptions<WmsSettings> options,
            IMapper mapper,
            ITechnologyRepository technologyRepository,
            ITrayRepository trayRepository,
            IBindCellService bindCellService)
            : base(logger, options, mapper)
        {
            this.technologyRepository = technologyRepository;
            this.trayRepository = trayRepository;
            this.bindCellService = bindCellService;
        }

        public async Task<ActionResult<TrayPO>> AutoBindTray(string lineCode, string trayBarcode, string stationCode, UserInfo userInfo)
        {
            var result = new ActionResult<TrayPO>("自动绑盘");
            try
            {
                var lineTechnologyRoutePO = await technologyRepository.GetLineStaionBindTechnologyRoute(lineCode, stationCode);
                if (lineTechnologyRoutePO == null)
                    return result.BusinessError($"线体:({lineCode}),站台:({stationCode}),绑定工艺路径数据未找到");

                var cellList = new List<CellDTO>();
                for (var i = 0; i < 36; i++)
                {
                    cellList.Add(new CellDTO()
                    {
                        CellPosition = i + 1,
                        CellBarcode = $"000AAAA000000000000{DateTime.Now.Ticks % 100000}"
                    });
                }

                var bindCellResult = await bindCellService.BindCell(trayBarcode, cellList, lineTechnologyRoutePO.TechnologyRouteCode, "1000", stationCode, userInfo);
                if (!bindCellResult.IsSuccess)
                    return result.Fail(bindCellResult);

                result.Data = bindCellResult.Data;
            }
            catch (Exception ex)
            {
                return result.Exception(ex);
            }

            return result;
        }
    }
}
